import { CheckAns } from "./CheckAns";

namespace LeetCode0888FairCandySwap {

    function fairCandySwap(A: number[], B: number[]): number[] {
        // 因为保证有解，简单判空即可
        if (!A || !B) return [];
        // 由题意可得，交换2数组中各一个值，使2数组各自和一样
        let cumA: number = 0;
        let setA: Set<number> = new Set();
        A.forEach((v: number) => {
            cumA += v;
            setA.add(v);
        });
        let cumB: number = 0;
        B.forEach((v: number) => {
            cumB += v;
        });
        const delta: number = (cumA - cumB) / 2;
        for (const v of B) {
            const want: number = delta + v;
            if (setA.has(want)) {
                return [want, v];
            }
        }
        return [];
    };

    // test
    const testData: { Alice: number[], Bob: number[], ans: number[] }[] = [
        { Alice: [1, 1], Bob: [2, 2], ans: [1, 2] },
        { Alice: [1, 2], Bob: [2, 3], ans: [1, 2] },
        { Alice: [2], Bob: [1, 3], ans: [2, 3] },
        { Alice: [1, 2, 5], Bob: [2, 4], ans: [5, 4] }
    ];
    for (const data of testData) {
        const ans = fairCandySwap(data.Alice, data.Bob);
        CheckAns(data, ans);
    }
}